// 生成界面id
const fsutil = require('./lib/fsutil')
const path = require('path')

module.exports = function(source, target) {
    let sourceList = [];
    fsutil.travel(source, sourceList);

    let targetList = [];
    fsutil.travel(target, targetList);

    console.log(sourceList);
    console.log(targetList);

    var panelMap = {};
    for (let i = 0; i < sourceList.length; i++) {
        let file = sourceList[i];
        if (file.indexOf(".json") > 0 && file.indexOf("all.json") < 0) {
            let content = fsutil.readJSON(file);
            if (content.node == "Skin") {
                let name = content.name;
                if (name) {
                    name = name.toLocaleLowerCase();
                    if (!panelMap[name]) {
                        panelMap[name] = {};
                    }
                    signId(content, panelMap[name])
                }
            }
        }
    }

    for (let i = 0; i < targetList.length; i++) {
        let file = targetList[i];
        let basename = path.basename(file, ".js");
        if (panelMap[basename]) {
            console.log(`修改面板${file}的内容`);
            updatefile(file, panelMap[basename])
        }
    }
}

function signId(element, panelMap) {
    let count = element.children ? element.children.length : 0;
    for (let i =0; i < count; i++) {
        signId(element.children[i], panelMap)
    }
    if (!count) {
        if (element.id) {
            panelMap[element.id] = element.node;
        }
    }
}

function updatefile(file, idmap) {
    var content = "";
    let str = fsutil.readString(file);
    let index = str.indexOf("export default class");
    if (index >= 0) {
        for (let key in idmap) {
            content += `//private let ${key}:${idmap[key]} \n`;
        }
        let fileContent = str.substr(0, index) + content + str.slice(index);
        fsutil.writeString(file, fileContent, "utf8")
    } else {

    }
}